<template>
    <StartLayout>
        <h2 class="title">重置密码</h2>
        <p class="subtitle">让配送更简单，让生意更轻松</p>

        <el-form ref="resetRef" :model="resetForm" :rules="resetRules" class="login-form">
            <el-form-item prop="email">
                <el-input v-model="resetForm.email" placeholder="邮箱" size="large" clearable class="custom-input">
                    <template #prefix>
                        <i class="el-icon-user" />
                    </template>
                </el-input>
            </el-form-item>

            <el-form-item prop="validCode">
                <div class="sms-code-wrapper">
                    <el-input v-model="resetForm.validCode" placeholder="邮箱验证码" size="large"
                        class="sms-code-input custom-input">
                        <template #prefix>
                            <i class="el-icon-message" />
                        </template>
                    </el-input>
                    <el-button :disabled="smsCodeDisabled" :loading="smsCodeLoading" class="sms-code-button"
                        @click="sendCode">
                        {{ smsCodeText }}
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="resetForm.password" type="password" placeholder="密码" size="large" show-password
                    class="custom-input">
                    <template #prefix>
                        <i class="el-icon-lock" />
                    </template>
                </el-input>
            </el-form-item>
            <div class="link-to-login">
                <el-link type="primary" :underline="false" @click="gotoLogin">返回登录页</el-link>
            </div>
            <el-form-item>
                <Button :loading="loading" @click="handleEnter">确定重置</Button>
            </el-form-item>
        </el-form>
    </StartLayout>
</template>

<script setup lang='ts'>
import { reactive, ref, computed } from 'vue'
import StartLayout from '@/components/layout/MainLayout.vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { getEmailCode } from '@/services/api/common'
import { resetPasssword } from '@/services/api/merchant'

const router = useRouter()

const resetRef = ref<FormInstance>()

const resetForm = reactive({
    email: '',
    password: '',
    validCode: ''
})

const loading = ref(false)

// 验证码
const smsCodeDisabled = ref(false)
const smsCodeLoading = ref(false)
const smsCodeCountdown = ref(0)

const smsCodeText = computed(() => {
    if (smsCodeLoading.value) return '发送中...'
    if (smsCodeCountdown.value > 0) return `${smsCodeCountdown.value}秒后重发`
    return '获取验证码'
})

const resetRules = computed<FormRules>(() => {
    return {
        email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        validCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { len: 6, message: '验证码为6位数字', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
            { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
        ]
    }
})

// 发送验证码
const sendCode = async () => {
    if (!resetForm.email) {
        ElMessage.error('请输入邮箱地址')
        return
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(resetForm.email)) {
        ElMessage.error('请输入正确的邮箱地址')
        return
    }
    smsCodeLoading.value = true

    // 模拟发送短信验证码
    setTimeout(() => {
        smsCodeLoading.value = false
        smsCodeDisabled.value = true
        smsCodeCountdown.value = 60
        getEmailCode(resetForm.email)
        // 倒计时
        const timer = setInterval(() => {
            smsCodeCountdown.value--
            if (smsCodeCountdown.value <= 0) {
                clearInterval(timer)
                smsCodeDisabled.value = false
            }
        }, 1000)

        ElMessage.success('验证码已发送，请注意查收')
    }, 1000)
}

const handleEnter = async () => {
    if (!resetRef.value) return
    await resetRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                const res = await resetPasssword(resetForm)
                if (res.code !== 200) {
                    ElMessage.error(res.msg)
                    return
                }
                ElMessage.success('密码重置成功')
                // 重置成功后可以跳转到登录页面
                router.push('/login')
            } catch (error) {
                ElMessage.error('重置密码失败，请稍后重试')
            } finally {
                loading.value = false
            }
        } else {
            ElMessage.error('请填写正确的信息')
        }
    })
}

const gotoLogin = () => {
    router.push({ name: 'login' })
}

</script>

<style lang='scss' scoped>
.link-to-login {
    text-align: right;
}
</style>